<template>
  <view class="patrol-container">
    <!-- 顶部筛选 -->
    <view class="filter-section">
      <view class="tab-buttons">
        <button 
          :class="['tab-btn', filterType === 'all' ? 'active' : '']" 
          @click="changeFilter('all')"
        >全部</button>
        <button 
          :class="['tab-btn', filterType === 'duzhi' ? 'active' : '']" 
          @click="changeFilter('duzhi')"
        >笃志楼</button>
        <button 
          :class="['tab-btn', filterType === 'boxue' ? 'active' : '']" 
          @click="changeFilter('boxue')"
        >博学楼</button>
      </view>
      
      <!-- 星期和时间段筛选 -->
      <view class="filter-row">
        <view class="filter-item">
          <text class="filter-label">星期:</text>
          <picker 
            mode="selector" 
            :range="weekdayOptions" 
            :value="weekdayIndex"
            range-key="label"
            @change="onWeekdayChange"
            class="filter-picker"
          >
            <view class="picker-view">
              {{ weekdayOptions[weekdayIndex].label }}
            </view>
          </picker>
        </view>
        
        <view class="filter-item">
          <text class="filter-label">时间段:</text>
          <picker 
            mode="selector" 
            :range="timeSlots" 
            :value="timeSlotIndex"
            range-key="label"
            @change="onTimeSlotChange"
            class="filter-picker"
          >
            <view class="picker-view">
              {{ timeSlots[timeSlotIndex].label }}
            </view>
          </picker>
        </view>
      </view>
    </view>

    <!-- 场地网格 -->
    <view class="location-grid">
      <view 
        v-for="(location, index) in displayLocations" 
        :key="index"
        :class="['location-card', getLocationStatusClass(location)]"
        @click="viewLocationDetail(location)"
      >
        <view class="location-header">
          <text class="location-name">{{ formatLocationName(location) }}</text>
          <text class="status-text">{{ location.statusText || '空闲' }}</text>
        </view>
        
        <!-- 不再显示具体课程名称，只显示状态 -->
      </view>
    </view>

    <!-- 空状态 -->
    <view v-if="displayLocations.length === 0" class="empty-state">
      <text class="empty-text">暂无场地数据</text>
    </view>

    <!-- 加载提示 -->
    <view class="load-more" v-if="loadStatus === 'loading'">
      <text class="loading-text">正在加载...</text>
    </view>
  </view>
</template>

<script>
import { getToken } from '@/utils/auth'
import config from '@/config'

export default {
  data() {
    return {
      searchText: '',
      filterType: 'all', // all, duzhi, boxue
      selectedWeekday: '', // 选中的星期，将在 onLoad 中设置为当前星期
      selectedTimeSlot: '', // 选中的时间段，将在 onLoad 中设置为当前时间段
      weekdayIndex: 0, // 星期选择器的索引
      timeSlotIndex: 0, // 时间段选择器的索引
      weekdayOptions: [
        { label: '星期一', value: '1' },
        { label: '星期二', value: '2' },
        { label: '星期三', value: '3' },
        { label: '星期四', value: '4' },
        { label: '星期五', value: '5' },
        { label: '星期六', value: '6' },
        { label: '星期日', value: '7' }
      ],
      timeSlots: [
        { label: '第1节: 8:30-9:15', value: '第1节: 8:30-9:15', startTime: '08:30', endTime: '09:15' },
        { label: '第2节: 9:25-10:10', value: '第2节: 9:25-10:10', startTime: '09:25', endTime: '10:10' },
        { label: '第3节: 10:30-11:15', value: '第3节: 10:30-11:15', startTime: '10:30', endTime: '11:15' },
        { label: '第4节: 11:25-12:10', value: '第4节: 11:25-12:10', startTime: '11:25', endTime: '12:10' },
        { label: '学习力: 14:00-14:45', value: '学习力: 14:00-14:45', startTime: '14:00', endTime: '14:45' },
        { label: '第6节: 14:55-15:40', value: '第6节: 14:55-15:40', startTime: '14:55', endTime: '15:40' },
        { label: '第7节: 16:00-16:45', value: '第7节: 16:00-16:45', startTime: '16:00', endTime: '16:45' },
        { label: '第8节: 16:55-17:40', value: '第8节: 16:55-17:40', startTime: '16:55', endTime: '17:40' },
        { label: '第9节: 19:00-19:45', value: '第9节: 19:00-17:45', startTime: '19:00', endTime: '19:45' },
        { label: '第10节: 19:55-20:40', value: '第10节: 19:55-20:40', startTime: '19:55', endTime: '20:40' }
      ], // 所有时间段列表
      locationList: [],
      scheduleList: [],
      violationMap: {}, // 违纪记录映射
      loadStatus: 'loading',
      page: 1,
      pageSize: 100
    }
  },
  computed: {
    // 过滤后显示的场地列表
    displayLocations() {
      let filtered = this.locationList
      
      // 按楼栋筛选
      if (this.filterType === 'duzhi') {
        // building_id = 1 是笃志楼
        filtered = filtered.filter(loc => loc.buildingId === 1)
      } else if (this.filterType === 'boxue') {
        // building_id = 2 是博学楼
        filtered = filtered.filter(loc => loc.buildingId === 2)
      }
      
      // 按搜索文本筛选
      if (this.searchText) {
        const search = this.searchText.toLowerCase()
        filtered = filtered.filter(loc => {
          const name = (loc.locationName || loc.name || '').toLowerCase()
          return name.includes(search)
        })
      }
      
      // 按场地名称和状态排序
      return filtered.sort((a, b) => {
        // 优先级1: 状态排序 - "有违纪" > "上课中" > "有课" > "空闲"
        const statusPriority = {
          'violation': -1, // 有违纪(最优先)
          'ongoing': 0,    // 上课中
          'scheduled': 1,  // 有课
          'free': 2        // 空闲
        }
        
        const priorityA = statusPriority[a.status] ?? 999
        const priorityB = statusPriority[b.status] ?? 999
        
        if (priorityA !== priorityB) {
          return priorityA - priorityB  // 状态优先级高的排前面
        }
        
        // 优先级2: 如果状态相同，按场地名称排序
        const nameA = a.locationName || a.name || ''
        const nameB = b.locationName || b.name || ''
        
        // 尝试数字排序
        const numA = parseInt(nameA)
        const numB = parseInt(nameB)
        if (!isNaN(numA) && !isNaN(numB)) {
          return numA - numB
        }
        
        // 字符串排序
        return nameA.localeCompare(nameB)
      })
    }
  },
  onLoad() {
    this.initCurrentDateTime()
    this.loadData()
  },
  onShow() {
    // 每次页面显示时刷新数据,确保显示最新的违纪状态
    this.loadData()
  },
  methods: {
    // 初始化当前日期时间
    initCurrentDateTime() {
      const now = new Date()
      
      // 设置当前星期（1=周一, 7=周日）
      let weekday = now.getDay()
      if (weekday === 0) weekday = 7 // 将周日从0转换为7
      this.selectedWeekday = weekday.toString()
      this.weekdayIndex = weekday - 1 // 索引从0开始，所以要减1
      
      // 设置当前时间段
      const currentTime = `${String(now.getHours()).padStart(2, '0')}:${String(now.getMinutes()).padStart(2, '0')}`
      
      // 查找当前时间所在的时间段
      const currentSlot = this.timeSlots.find(slot => {
        return currentTime >= slot.startTime && currentTime <= slot.endTime
      })
      
      if (currentSlot) {
        this.selectedTimeSlot = currentSlot.value
        this.timeSlotIndex = this.timeSlots.findIndex(s => s.value === currentSlot.value)
      } else {
        // 如果不在任何时间段内，找最近的下一个时间段
        const nextSlot = this.timeSlots.find(slot => currentTime < slot.startTime)
        if (nextSlot) {
          this.selectedTimeSlot = nextSlot.value
          this.timeSlotIndex = this.timeSlots.findIndex(s => s.value === nextSlot.value)
        } else {
          // 如果已经过了所有时间段，选择第一个
          this.selectedTimeSlot = this.timeSlots[0].value
          this.timeSlotIndex = 0
        }
      }
      
      // console.log('当前星期:', this.selectedWeekday)
      // console.log('当前时间段:', this.selectedTimeSlot)
    },
    // 加载数据
    async loadData() {
      this.loadStatus = 'loading'
      await this.getLocationList()
      await this.getScheduleList()
      await this.getViolationRecords() // 获取违纪记录
      this.matchScheduleToLocation()
      this.loadStatus = 'loaded'
    },
    
    // 获取场地列表（循环分页获取所有数据）
    async getLocationList() {
      try {
        const token = getToken()
        if (!token) {
          this.$modal.msgError('请先登录')
          uni.reLaunch({ url: '/pages/login' })
          return
        }

        let allLocations = []
        let pageNo = 1
        const pageSize = 100
        
        // console.log('开始获取场地数据...')

        // 循环获取所有分页数据
        while (true) {
          const response = await uni.request({
            url: config.baseUrl + '/admin-api/ao/class-location/page',
            method: 'GET',
            header: {
              'Authorization': 'Bearer ' + token,
              'tenant-id': '1',
              'Content-Type': 'application/json'
            },
            data: {
              pageNo: pageNo,
              pageSize: pageSize
            }
          })

          const [error, res] = response
          
          if (!error && res.data.code === 0) {
            const list = res.data.data?.list || []
            // console.log(`第${pageNo}页获取到${list.length}条场地数据`)
            
            allLocations = allLocations.concat(list)
            
            // 如果当前页数据少于pageSize，说明已经是最后一页
            if (list.length < pageSize) {
              break
            }
            
            pageNo++
          } else {
            break
          }
        }
        
        // console.log(`✅ 场地数据获取完成，共${allLocations.length}条记录`)

        this.locationList = allLocations.map(loc => ({
          ...loc,
          name: loc.locationName,
          currentClass: null,
          statusText: '空闲',
          status: 'free'
        }))
        
      } catch (err) {
        // 获取场地列表失败
      }
    },
    
    // 获取今日课表(循环分页获取班级课表和实训室课表)
    async getScheduleList() {
      try {
        const token = getToken()
        if (!token) {
          return
        }

        // console.log('开始获取课表数据...')

        // 循环分页获取班级课表
        const vocationalData = await this.fetchAllSchedules(
          config.baseUrl + '/admin-api/ao/vocational-class-schedule/page',
          token,
          '班级课表'
        )

        // 循环分页获取实训室课表
        const labData = await this.fetchAllSchedules(
          config.baseUrl + '/admin-api/ao/lab-schedule/page',
          token,
          '实训室课表'
        )

        // 合并两种课表
        this.scheduleList = [...vocationalData, ...labData]
        // console.log('📊 课表数据加载完成，共', this.scheduleList.length, '条 (班级:', vocationalData.length, '+ 实训室:', labData.length, ')')
        
        // if (this.scheduleList.length > 0) {
        //   console.log('课表示例:', this.scheduleList[0])
        //   // 查看课表数据结构
        //   const firstSchedule = this.scheduleList[0]
        //   console.log('课表字段分析:', {
        //     id: firstSchedule.id,
        //     className: firstSchedule.className,
        //     classroom: firstSchedule.classroom,
        //     classSection: firstSchedule.classSection,
        //     mondayCourse: firstSchedule.mondayCourse ? '有' : '无',
        //     tuesdayCourse: firstSchedule.tuesdayCourse ? '有' : '无',
        //     wednesdayCourse: firstSchedule.wednesdayCourse ? '有' : '无',
        //     thursdayCourse: firstSchedule.thursdayCourse ? '有' : '无',
        //     fridayCourse: firstSchedule.fridayCourse ? '有' : '无',
        //     saturdayCourse: firstSchedule.saturdayCourse ? '有' : '无',
        //     sundayCourse: firstSchedule.sundayCourse ? '有' : '无'
        //   })
        // } else {
        //   console.warn('⚠️ 警告: 两个课表API都返回0条数据!')
        // }
        
      } catch (err) {
        // 获取课表异常
      }
    },

    // 循环分页获取课表数据(通用方法)
    async fetchAllSchedules(url, token, name) {
      const allData = []
      let pageNo = 1
      const pageSize = 100 // 每页100条(最大限制)
      
      try {
        while (true) {
          const response = await uni.request({
            url: url,
            method: 'GET',
            header: {
              'Authorization': 'Bearer ' + token,
              'tenant-id': '1',
              'Content-Type': 'application/json'
            },
            data: {
              pageNo: pageNo,
              pageSize: pageSize
            }
          })

          const [error, res] = response
          
          if (error) {
            break
          }
          
          if (res.data.code !== 0) {
            break
          }

          const list = res.data.data?.list || []
          const total = res.data.data?.total || 0
          
          // console.log(`${name}第${pageNo}页: ${list.length}条 (总计:${total})`)
          
          if (list.length > 0) {
            allData.push(...list)
          }

          // 如果本页数据少于pageSize，说明已经是最后一页
          if (list.length < pageSize) {
            break
          }

          pageNo++
        }

        // console.log(`✅ ${name}数据获取完成: ${allData.length}条`)
        return allData
        
      } catch (err) {
        return allData
      }
    },
    
    // 获取违纪记录
    async getViolationRecords() {
      try {
        const token = getToken()
        if (!token) {
          return
        }
        
        // 根据选择的星期计算本周对应的日期
        const today = new Date()
        const currentWeekday = today.getDay() || 7  // 0=周日转换为7
        const selectedWeekdayNum = parseInt(this.selectedWeekday || currentWeekday)
        
        // 计算本周一的日期
        const monday = new Date(today)
        monday.setDate(today.getDate() - (currentWeekday - 1))
        
        // 计算目标日期（本周的星期X）
        const targetDate = new Date(monday)
        targetDate.setDate(monday.getDate() + (selectedWeekdayNum - 1))
        
        const dateStr = `${targetDate.getFullYear()}-${String(targetDate.getMonth() + 1).padStart(2, '0')}-${String(targetDate.getDate()).padStart(2, '0')}`
        
        const requestData = {
          pageNo: 1,
          pageSize: 100,
          classDate: [`${dateStr} 00:00:00`, `${dateStr} 23:59:59`]
        }
        
        const response = await uni.request({
          url: config.baseUrl + '/admin-api/ao/patrol/page',
          method: 'GET',
          header: {
            'Authorization': 'Bearer ' + token,
            'tenant-id': '1',
            'Content-Type': 'application/json'
          },
          data: requestData
        })
        
        const [error, res] = response
        
        if (!error && res.data.code === 0) {
          const violationList = res.data.data?.list || []
          
          // 自动删除"无违纪"记录
          const noViolationRecords = violationList.filter(item => 
            item.violationType === '无违纪' || item.violationCount === 0
          )
          
          if (noViolationRecords.length > 0) {
            // 批量删除无违纪记录
            for (const record of noViolationRecords) {
              try {
                await uni.request({
                  url: config.baseUrl + `/admin-api/ao/patrol/delete?id=${record.id}`,
                  method: 'DELETE',
                  header: {
                    'Authorization': 'Bearer ' + token,
                    'tenant-id': '1'
                  }
                })
              } catch (err) {
                // 删除失败，忽略错误
              }
            }
          }
          
          // 创建违纪记录映射: key=教室名_时间段, value=违纪记录数组
          // 只保留真正有违纪的记录(violationType != "无违纪")
          this.violationMap = {}
          violationList.forEach(item => {
            // 过滤掉"无违纪"记录
            if (item.violationType === '无违纪' || item.violationCount === 0) {
              return  // 跳过无违纪记录
            }
            
            const normalizedTime = this.normalizeTimeFormat(item.classTime)  // 统一时间格式
            const key = `${item.classroom}_${normalizedTime}`
            if (!this.violationMap[key]) {
              this.violationMap[key] = []
            }
            this.violationMap[key].push(item)
          })
          
          // console.log('违纪记录映射(已过滤无违纪):', this.violationMap)  // 调试输出
        }
      } catch (err) {
        // 获取违纪记录失败
      }
    },
    
    // 匹配课表到场地
    matchScheduleToLocation() {
      const now = new Date()
      const currentTime = `${String(now.getHours()).padStart(2, '0')}:${String(now.getMinutes()).padStart(2, '0')}`
      
      // 获取当前星期几(1=周一, 7=周日)
      let currentWeekday = now.getDay()
      if (currentWeekday === 0) currentWeekday = 7
      
      // 使用选中的星期，如果没选则使用当前星期
      const targetWeekday = this.selectedWeekday || currentWeekday.toString()
      
      let matchedCount = 0
      let debugCount = 0 // 详细调试前5次失败
      
      this.locationList.forEach((location, index) => {
        const locationName = location.locationName || location.name
        const buildingId = location.buildingId
        
        // 重置状态
        location.currentClass = null
        location.statusText = '空闲'
        location.status = 'free'
        location.schedule = null
        
        // 遍历课表，查找该场地在指定星期、指定时间段的课程
        for (const schedule of this.scheduleList) {
          // 检查该课表是否在指定时间段
          if (this.selectedTimeSlot && !this.isScheduleInTimeSlot(schedule)) {
            continue
          }
          
          // 获取课程信息
          const courseInfo = this.getCourseInfoByWeekday(schedule, targetWeekday)
          
          // // 临时调试:查看前几条匹配详情
          // if (index === 0 && debugCount < 5) {
          //   debugCount++
          //   console.log(`[调试] 场地"${locationName}" 尝试匹配课表:`, {
          //     课表ID: schedule.id,
          //     班级: schedule.className,
          //     classroom: schedule.classroom,
          //     classSection: schedule.classSection,
          //     时间段匹配: this.selectedTimeSlot ? this.isScheduleInTimeSlot(schedule) : '未选择',
          //     courseInfo前50字: courseInfo ? courseInfo.substring(0, 50) : null,
          //     buildingId: buildingId
          //   })
          // }
          
          if (!courseInfo) continue
          
          // 检查楼栋匹配
          const classroom = schedule.classroom || ''
          const labName = schedule.labName || schedule.lab_name || ''
          const classroomPrefix = classroom.charAt(0)
          
          let buildingMatch = false
          
          // 实训室课表: 通过 lab_name 判断(格式: "本校区-笃志楼-大舞蹈室")
          if (labName) {
            if (buildingId === 1 && labName.includes('笃志楼')) {
              buildingMatch = true
            } else if (buildingId === 2 && labName.includes('博学楼')) {
              buildingMatch = true
            }
          }
          // 班级课表: 通过 classroom 判断(格式: "D201", "B316")
          else if (classroom) {
            if (buildingId === 1 && classroomPrefix === 'D') {
              buildingMatch = true
            } else if (buildingId === 2 && classroomPrefix === 'B') {
              buildingMatch = true
            }
          } else {
            // 如果都为空，继续检查课程信息中的场地
            buildingMatch = true
          }
          
          if (!buildingMatch) {
            continue
          }
          
          // 匹配逻辑
          let isMatch = false
          
          // 方式1: 实训室课表 - 使用 lab_name 字段匹配
          // lab_name 格式: "本校区-笃志楼-大舞蹈室"
          if (labName) {
            // 提取最后一段场地名(去掉"本校区-笃志楼-"前缀)
            const labLocationName = labName.split('-').pop() || ''
            // 精确匹配场地名,避免"机房1"匹配到"机房10"
            if (labLocationName && locationName === labLocationName) {
              isMatch = true
            }
          }
          // 方式2: 班级课表 - 解析课程信息第三行(场地名)
          // 课程信息格式: "课程名\r\n教师名\r\n场地名"
          else if (classroom) {
            const lines = courseInfo.split(/[\r\n]+/).filter(line => line.trim())
            const actualLocation = lines[2] || '' // 第三行是实际上课地点
            
            // 优先精确匹配课程信息中的地点
            if (actualLocation && actualLocation === locationName) {
              isMatch = true
            }
            // 如果课程信息中没有地点,则用 classroom 字段匹配
            else if (!actualLocation) {
              // 提取classroom中的数字部分(B213 -> 213)
              const classroomNumber = classroom.replace(/^[A-Z]+/, '')
              // 精确匹配场地名或教室号,避免"201"匹配到"2011"
              if (locationName === classroomNumber || locationName === classroom) {
                isMatch = true
              }
            }
          }
          
          if (isMatch) {
            matchedCount++
            
            // 提取课程名称
            const courseName = this.extractCourseName(courseInfo)
            location.currentClass = courseName
            
            // 检查是否有违纪记录
            // 需要将 classSection (如 "6") 转换为时间段格式 (如 "14:55-15:40")
            const sectionNumber = schedule.classSection.toString().trim()
            const sectionMatch = sectionNumber.match(/\d+/)
            let timeSlotStr = ''
            
            if (sectionMatch) {
              const sectionIndex = parseInt(sectionMatch[0]) - 1 // 第6节 -> index 5
              if (this.timeSlots[sectionIndex]) {
                const slot = this.timeSlots[sectionIndex]
                timeSlotStr = this.normalizeTimeFormat(`${slot.startTime}-${slot.endTime}`)  // 统一时间格式
              }
            }
            
            const locationKey = `${this.formatLocationName(location)}_${timeSlotStr}`
            const hasViolation = this.violationMap[locationKey] && this.violationMap[locationKey].length > 0
            
            // 状态判断
            if (hasViolation) {
              // 有违纪记录,显示红色"有违纪"
              location.statusText = '有违纪'
              location.status = 'violation'
              location.violations = this.violationMap[locationKey] // 保存违纪记录
            } else if (this.selectedTimeSlot) {
              // 没有违纪,如果选择了具体时间段,则显示"上课中"
              location.statusText = '上课中'
              location.status = 'ongoing'
            } else {
              // 没有违纪,如果没选时间段,显示"有课"
              location.statusText = '有课'
              location.status = 'scheduled'
            }
            
            location.schedule = schedule
            
            break
          }
        }
      })
      
      // 为所有教室(包括空闲教室)检查违纪记录
      this.locationList.forEach(location => {
        // 如果已经有违纪状态,跳过
        if (location.status === 'violation') return
        
        // 获取时间段字符串
        let timeSlotStr = ''
        if (this.selectedTimeSlot) {
          const match = this.selectedTimeSlot.match(/第(\d+)节/)
          if (match) {
            const sectionIndex = parseInt(match[1]) - 1
            if (this.timeSlots[sectionIndex]) {
              const slot = this.timeSlots[sectionIndex]
              timeSlotStr = this.normalizeTimeFormat(`${slot.startTime}-${slot.endTime}`)  // 统一时间格式
            }
          }
        }
        
        // 检查违纪记录
        if (timeSlotStr) {
          const locationKey = `${this.formatLocationName(location)}_${timeSlotStr}`
          const hasViolation = this.violationMap[locationKey] && this.violationMap[locationKey].length > 0
          
          if (hasViolation) {
            // 空闲教室也可能有违纪记录
            location.statusText = '有违纪'
            location.status = 'violation'
            location.violations = this.violationMap[locationKey]
          }
        }
      })
      
      // console.log(`✅ 匹配完成: ${matchedCount}/${this.locationList.length} 个场地有课`)
      
      // 如果没有匹配到任何课程，提示用户
      if (matchedCount === 0 && this.scheduleList.length > 0) {
        // console.warn('⚠️ 未匹配到任何课程，可能原因:')
        // console.warn('1. 当前选择的星期没有课程安排')
        // console.warn('2. 当前选择的时间段没有课程')
        // console.warn('3. 场地名称格式与课表中的不匹配')
        
        // 统计各星期的课程数量
        // const weekdayStats = {}
        // for (let w = 1; w <= 7; w++) {
        //   let count = 0
        //   for (const sch of this.scheduleList) {
        //     if (this.getCourseInfoByWeekday(sch, w.toString())) {
        //       count++
        //       break
        //     }
        //   }
        //   weekdayStats[`星期${w}`] = count > 0 ? '有课' : '无课'
        // }
        // console.log('各星期课程统计:', weekdayStats)
      }
    },
    
    // 检查课表是否在指定时间段
    isScheduleInTimeSlot(schedule) {
      if (!schedule.classSection) return false
      
      const section = schedule.classSection.toString().trim()
      
      // 方案1: 如果 selectedTimeSlot 是 "第X节" 格式
      const periodMatch = this.selectedTimeSlot.match(/第(\d+)节/)
      if (periodMatch) {
        const periodNum = periodMatch[1]
        
        // 清理换行符,统一格式
        const cleanSection = section.replace(/[\r\n]+/g, ' ').trim()
        
        // 提取所有节次数字
        const sectionMatch = cleanSection.match(/^(\d+)(?:\s|第|节|$)/) || cleanSection.match(/第(\d+)节/)
        
        if (sectionMatch) {
          const sectionNum = sectionMatch[1]
          return sectionNum === periodNum
        }
        return false
      }
      
      // 方案2: 如果 selectedTimeSlot 是 "学习力: 14:00-14:45" 这种格式
      // 需要根据时间段找到对应的节次，然后匹配
      const timeMatch = this.selectedTimeSlot.match(/(\d{1,2}):(\d{2})-(\d{1,2}):(\d{2})/)
      if (timeMatch) {
        const startTime = `${timeMatch[1].padStart(2, '0')}:${timeMatch[2]}`
        const endTime = `${timeMatch[3].padStart(2, '0')}:${timeMatch[4]}`
        
        // 根据时间段查找对应的节次
        const slotIndex = this.timeSlots.findIndex(slot => 
          slot.startTime === startTime && slot.endTime === endTime
        )
        
        if (slotIndex >= 0) {
          // slotIndex + 1 就是节次（第1节、第2节...）
          const periodNum = (slotIndex + 1).toString()
          
          // 匹配 classSection 中的节次
          const cleanSection = section.replace(/[\r\n]+/g, ' ').trim()
          const sectionMatch = cleanSection.match(/^(\d+)(?:\s|第|节|$)/) || cleanSection.match(/第(\d+)节/)
          
          if (sectionMatch) {
            const sectionNum = sectionMatch[1]
            return sectionNum === periodNum
          }
        }
      }
      
      return false
    },
    
    // 根据星期获取课程信息
    getCourseInfoByWeekday(schedule, weekday) {
      // 班级课表字段
      const classScheduleMap = {
        '1': 'mondayCourse',
        '2': 'tuesdayCourse',
        '3': 'wednesdayCourse',
        '4': 'thursdayCourse',
        '5': 'fridayCourse',
        '6': 'saturdayCourse',
        '7': 'sundayCourse'
      }
      
      // 实训室课表字段
      const labScheduleMap = {
        '1': 'mondayUsage',
        '2': 'tuesdayUsage',
        '3': 'wednesdayUsage',
        '4': 'thursdayUsage',
        '5': 'fridayUsage',
        '6': 'saturdayUsage',
        '7': 'sundayUsage'
      }
      
      // 优先尝试班级课表字段
      const classField = classScheduleMap[weekday]
      if (classField && schedule[classField]) {
        return schedule[classField]
      }
      
      // 然后尝试实训室课表字段
      const labField = labScheduleMap[weekday]
      if (labField && schedule[labField]) {
        return schedule[labField]
      }
      
      return null
    },
    
    // 提取课程名称
    extractCourseName(courseInfo) {
      if (!courseInfo) return '上课中'
      
      // 课程信息格式: "课程名\r\n教师名\r\n场地名" 或 "课程名 教师名 场地名"
      const lines = courseInfo.split(/[\r\n]+/).filter(line => line.trim())
      if (lines.length > 0) {
        // 第一行通常是课程名
        return lines[0].trim()
      }
      
      // 如果没有换行，尝试按空格分割
      const parts = courseInfo.split(/\s+/).filter(part => part.trim())
      return parts.length > 0 ? parts[0] : '上课中'
    },
    
    // 获取今天日期
    getTodayDate() {
      const today = new Date()
      const year = today.getFullYear()
      const month = String(today.getMonth() + 1).padStart(2, '0')
      const day = String(today.getDate()).padStart(2, '0')
      return `${year}-${month}-${day}`
    },
    
    // 根据选中的星期计算本周对应的日期
    getDateByWeekday(weekday) {
      const today = new Date()
      const currentWeekday = today.getDay() || 7 // 0=周日转为7
      const targetWeekday = parseInt(weekday)
      
      // 计算本周一的日期
      const monday = new Date(today)
      monday.setDate(today.getDate() - (currentWeekday - 1))
      
      // 计算目标日期（本周的星期X）
      const targetDate = new Date(monday)
      targetDate.setDate(monday.getDate() + (targetWeekday - 1))
      
      // 格式化为 YYYY-MM-DD
      const year = targetDate.getFullYear()
      const month = String(targetDate.getMonth() + 1).padStart(2, '0')
      const day = String(targetDate.getDate()).padStart(2, '0')
      return `${year}-${month}-${day}`
    },
    
    // 获取星期几的文本
    getWeekdayText(weekday) {
      const weekdayMap = {
        '1': '星期一',
        '2': '星期二',
        '3': '星期三',
        '4': '星期四',
        '5': '星期五',
        '6': '星期六',
        '7': '星期日'
      }
      return weekdayMap[weekday] || ''
    },
    
    // 格式化场地名称显示(添加建筑前缀)
    formatLocationName(location) {
      const name = location.locationName || location.name || ''
      const buildingId = location.buildingId
      
      // 如果名称已经包含前缀(D或B开头),直接返回
      if (/^[DB]\d/.test(name)) {
        return name
      }
      
      // 根据建筑ID添加前缀
      if (buildingId === 1) {
        return 'D' + name  // 笃志楼
      } else if (buildingId === 2) {
        return 'B' + name  // 博学楼
      }
      
      return name
    },
    
    // 统一时间格式: 移除前导0,例如 "08:30-09:15" -> "8:30-9:15"
    normalizeTimeFormat(timeStr) {
      if (!timeStr) return ''
      return timeStr.replace(/0(\d)/g, '$1')  // 移除所有前导0
    },
    
    // 切换筛选
    changeFilter(type) {
      this.filterType = type
    },
    
    // 搜索场地
    searchLocation() {
      // 搜索文本改变时会自动触发 computed 重新计算
    },
    
    // 搜索输入
    onSearchInput(e) {
      this.searchText = e.target.value || e.detail.value
    },
    
    // 星期选择改变
    onWeekdayChange(e) {
      const index = e.detail.value
      this.weekdayIndex = index
      this.selectedWeekday = this.weekdayOptions[index].value
      this.loadData()
    },
    
    // 时间段选择改变
    onTimeSlotChange(e) {
      const index = e.detail.value
      this.timeSlotIndex = index
      this.selectedTimeSlot = this.timeSlots[index].value
      this.loadData()
    },
    
    // 查看场地详情
    viewLocationDetail(location) {
      // 空闲教室也允许点击,用于手动添加违纪记录
      
      let courseName = ''
      let teacherName = ''
      let classLocation = ''
      let className = ''
      let scheduleId = ''
      
      if (location.schedule) {
        // 有课程时,解析课程信息
        const schedule = location.schedule
        const courseInfo = this.getCourseInfoByWeekday(schedule, this.selectedWeekday || '1')
        const lines = courseInfo ? courseInfo.split(/[\r\n]+/).filter(line => line.trim()) : []
        
        // 判断是否为实训室课表(通过 labName 字段)
        const isLabSchedule = schedule.labName || schedule.lab_name
        
        if (isLabSchedule) {
          // 实训室课表格式: "年级 班级名\r\n课程名 教师名"
          const classLine = lines[0] || ''
          
          // 分离年级和班级名
          const gradeMatch = classLine.match(/^(高[一二三]|中[一二三])\s+(.+)$/)
          if (gradeMatch) {
            className = gradeMatch[2]
            className = className.replace(/^0+/, '')
          } else {
            className = classLine
            className = className.replace(/^0+/, '')
          }
          
          // 第二行是 "课程名 教师名"
          const courseAndTeacher = lines[1] || ''
          const parts = courseAndTeacher.split(/\s+/).filter(p => p.trim())
          courseName = parts[0] || location.currentClass || ''
          teacherName = parts.slice(1).join(' ') || ''
          
          // 实训室场地名从 lab_name 提取
          const labName = schedule.labName || schedule.lab_name || ''
          classLocation = labName.split('-').pop() || this.formatLocationName(location)
        } else {
          // 班级课表格式: "课程名\r\n教师名\r\n场地名"
          courseName = lines[0] || location.currentClass || ''
          teacherName = lines[1] || schedule.classTeacher || ''
          classLocation = lines[2] || this.formatLocationName(location)
          className = schedule.className || ''
          className = className.replace(/^0+/, '')
        }
        
        scheduleId = schedule.id
      } else {
        // 空闲教室,提供场地名、日期、时间信息,其他由用户手动填写
        classLocation = this.formatLocationName(location)
      }
      
      // 获取选中的时间段信息(无论是否有课程都需要)
      // 如果没有选择时间段,使用当前时间段或第一个时间段
      const currentSelectedSlot = this.selectedTimeSlot || this.timeSlots[0]?.value || ''
      const selectedSlot = this.timeSlots.find(slot => slot.value === currentSelectedSlot)
      const startTime = selectedSlot ? selectedSlot.startTime : ''
      const endTime = selectedSlot ? selectedSlot.endTime : ''
      
      // 获取星期几的文本和实际日期(无论是否有课程都需要)
      // 如果没有选择星期,使用当前星期
      const currentWeekday = this.selectedWeekday || (() => {
        const now = new Date()
        let weekday = now.getDay()
        if (weekday === 0) weekday = 7
        return weekday.toString()
      })()
      const weekdayText = this.getWeekdayText(currentWeekday)
      const actualDate = this.getDateByWeekday(currentWeekday)
      
      // 构建详情页参数
      const params = {
        scheduleId: scheduleId,
        courseName: courseName,
        teacherName: teacherName,
        className: className,
        classLocation: classLocation,  // 上课地点(必有)
        classDate: actualDate,          // 上课日期(必有)
        weekdayText: weekdayText,       // 星期文本(必有)
        startTime: startTime,           // 开始时间(必有)
        endTime: endTime,               // 结束时间(必有)
        classroom: location.schedule?.classroom || this.formatLocationName(location), // 空闲时用场地名
        hasViolation: location.status === 'violation' ? '1' : '0', // 是否有违纪
        violationId: location.violations && location.violations.length > 0 ? location.violations[0].id : '' // 违纪记录ID
      }
      
      // console.log('跳转详情页参数:', params)
      
      // 使用 URL 参数传递
      const queryString = Object.keys(params)
        .map(key => `${key}=${encodeURIComponent(params[key] || '')}`)
        .join('&')
      
      const detailUrl = `/pages/patrol/detail?${queryString}`
      // console.log('跳转URL:', detailUrl)
      
      uni.navigateTo({
        url: detailUrl,
        success: () => {
          // console.log('跳转成功')
        },
        fail: (err) => {
          uni.showToast({
            title: '跳转失败',
            icon: 'none'
          })
        }
      })
    },
    
    // 获取场地状态样式
    getLocationStatusClass(location) {
      return location.status || 'free'
    }
  }
}
</script>

<style lang="scss" scoped>
.patrol-container {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding-bottom: 20px;
}

.filter-section {
  background-color: #fff;
  padding: 15px;
  margin-bottom: 10px;
}

.tab-buttons {
  display: flex;
  gap: 8px;
  margin-bottom: 15px;
}

.tab-btn {
  flex: 1;
  padding: 8px 12px;
  background-color: #f5f5f5;
  border: none;
  border-radius: 6px;
  font-size: 13px;
  color: #666;
  transition: all 0.3s;
}

.tab-btn.active {
  background-color: #007aff;
  color: #fff;
}

.filter-row {
  display: flex;
  gap: 10px;
  margin-bottom: 15px;
}

.filter-item {
  flex: 1;
  display: flex;
  align-items: center;
  gap: 8px;
}

.filter-label {
  font-size: 13px;
  color: #666;
  white-space: nowrap;
}

.filter-picker {
  flex: 1;
}

.picker-view {
  padding: 8px 10px;
  border: 1px solid #ddd;
  border-radius: 6px;
  font-size: 13px;
  color: #333;
  background-color: #fff;
  text-align: center;
}

.filter-select {
  flex: 1;
  padding: 8px 10px;
  border: 1px solid #ddd;
  border-radius: 6px;
  font-size: 13px;
  color: #333;
  background-color: #fff;
  appearance: auto;
  -webkit-appearance: menulist;
  -moz-appearance: menulist;
}

.filter-select:focus {
  outline: none;
  border-color: #007aff;
}

.filter-select option {
  color: #333;
  background-color: #fff;
  padding: 8px;
}

.search-box {
  width: 100%;
}

.search-input {
  width: 100%;
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 6px;
  font-size: 14px;
  box-sizing: border-box;
}

.location-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 10px;
  padding: 10px;
}

.location-card {
  background-color: #fff;
  border-radius: 12px;
  padding: 15px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  border-left: 4px solid #ddd;
  cursor: pointer;
  transition: all 0.3s;
  min-height: 80px;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.location-card:active {
  transform: scale(0.95);
}

.location-card.free {
  border-left-color: #ddd;
}

.location-card.scheduled {
  // border-left-color: #ef4444;
  background: linear-gradient(135deg, #fff 0%, #fee 100%);
}

.location-card.ongoing {
  // border-left-color: #10b981;
  background: linear-gradient(135deg, #fff 0%, #f0fdf4 100%);
}

.location-card.violation {
  // border-left-color: #dc2626;
  background: linear-gradient(135deg, #fff 0%, #fee2e2 100%);
}

.location-header {
  margin-bottom: 8px;
}

.location-name {
  font-size: 18px;
  font-weight: bold;
  color: #333;
  display: block;
  margin-bottom: 4px;
}

.status-text {
  font-size: 11px;
  color: #999;
  display: block;
}

.location-card.ongoing .status-text {
  color: #10b981;
  font-weight: 500;
}

.location-card.scheduled .status-text {
  color: #ef4444;
  font-weight: 500;
}

.location-card.violation .status-text {
  color: #dc2626;
  font-weight: bold;
}

.location-info {
  display: flex;
  align-items: center;
  gap: 4px;
  margin-top: 5px;
}

.info-icon {
  font-size: 12px;
}

.info-text {
  font-size: 12px;
  color: #666;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 100px 0;
  background-color: #fff;
  border-radius: 12px;
  margin: 10px;
}

.empty-text {
  font-size: 14px;
  color: #999;
}

.load-more {
  padding: 20px 0;
  text-align: center;
}

.loading-text {
  font-size: 14px;
  color: #999;
}
</style>
